#! /usr/bin/env python3 
# coding: utf-8


import os
import tempfile
import time,random
import base64
import requests
from flask import Flask
from flask import render_template,request,make_response
from flask import abort,jsonify
from flask import url_for


class Config(object):
    ROOT = os.path.abspath(os.path.dirname(__name__))
    STATIC_FOLDER = ROOT
    TEMPLATE_FOLDER = ROOT
    IMAGE_FILTER = ('jpg','gif','png','jpeg','bmp')
    MOCK_BROWSER = {
        'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
        'Accept':'text/html;q=0.9,*/*;q=0.8',
        'Accept-Charset':'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
        'Accept-Encoding':'gzip',
        'Connection':'close',
        'Referer': None #注意如果依然不能抓取，这里可以设置抓取网站的host
    }


app = Flask(__name__,template_folder=Config.TEMPLATE_FOLDER,static_folder=Config.STATIC_FOLDER)
app.config.from_object(Config)


@app.route('/',methods=['GET','POST'])
def index():
    '''My web index html definition

    Website Index Page
    '''
    return render_template('index.html')


@app.route('/image/',methods=['GET','POST'])
def image():
    '''头像图片处理

    接受客户端上传的头像url，获取图片到本地，传回地址给客户端
    '''
    if request.method.lower() == 'post':
        url = request.form.get('imageurl')
        if url is not None and url.endswith(app.config.get('IMAGE_FILTER','jpg')):
            suff = '.'+url.split('.')[-1]
            tmpname = time.strftime("%Y%m%d%H%M%S")
            rsp = requests.get(url,headers=app.config.get('MOCK_BROWSER',Config.MOCK_BROWSER),timeout=2000)
            if rsp and rsp.status_code == 200:
                timgfile = tempfile.mktemp(prefix=tmpname,suffix=suff,dir='tmp')
                with open(timgfile,'wb') as fp:
                    fp.write(rsp.content)
                    fp.flush()
            else: 
                abort(500)
            filepath = url_for('static',filename=timgfile.replace('\\','/'))
            return jsonify(imagepath=filepath)
    else:
        abort(501)
    abort(404)



if __name__=='__main__':
    app.run(debug=True) 
